package titt.util.io.loader;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class FileStream {
	
	private InputStream in;
	private final File f;
	private final String absFilename;
	private final FileStreamLoader fls;
	
	public FileStream(String absFilename, FileStreamLoader fls, File f) {
		this.f = f;
		this.absFilename = absFilename;
		this.fls = fls;
		
	}
	
	public InputStream getInputStream() {
		if(in == null)
			in = new BufferedInputStream(fls.loadStream(absFilename));
		return in;
	}
	
	public String getPath() {
		return absFilename;
	}
	
	public String getName() {
		return f.getName();
	}
	
	public long lastModified() {
		return f.exists()? f.lastModified() : -1; 
	}
	
	public byte[] readFile() throws Exception {
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		
		in = getInputStream();
		
		byte[] buf = new byte[1024];
		int len;
			
		while((len = in.read(buf)) != -1)
			bout.write(buf, 0, len);
		
		bout.close();
		
		close();
		
		return bout.toByteArray();

	}
	
	public boolean exists() {
		return in != null;
	}
	
	public void close() {
		try {
			if(in != null)
				in.close();
		} 
		catch (IOException e) {}
		in = null;
	}
}
